package optional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author Klys
 * @Date 2023/6/21
 * @Description
 * @Version 1.0
 */
public class StreamTest {

    public static void main(String[] args) {

        User user1 = new User(1, "klys");
        User user2 = new User(1, "liuyusong");
        User user3 = new User(1, "xiaoming");
        List<User> userList = Arrays.asList(user1, user2, user3);

//        过滤出年龄大于3的所有用户
        List<User> collect = userList.stream()
                .filter(obj -> obj.getAge() > 2).collect(Collectors.toList());
        //System.out.println(collect);

//        迭代器遍历修改
        Iterator<User> iterator = userList.iterator();
        while (iterator.hasNext()) {
            iterator.next().setName("update");
        }

//        finFirst拿到有序流中的第一个对象
        User other = new User(90, "other");
        User orElse = userList.stream()
                .filter(user -> user.getAge() > 0)
                .findFirst().orElseThrow(() -> new RuntimeException("条件不存在"));
        System.out.println(orElse);

//         一个两参数的reduce聚合操作
        Optional<User> reduce1 = userList.stream()
                .filter(user -> user.getAge() > 0)
                .reduce((a, b) -> new User(a.getAge() + b.getAge(), a.getName() + b.getName()));
        System.out.println(reduce1);

        User reduce2 = userList.stream()
                .filter(user -> user.getAge() > 0)
                .reduce(other, (a, b) -> new User(a.getAge() + b.getAge(), a.getName() + b.getName() + other.getName()));
        System.out.println(reduce2);

//        reduce规约操作
//        reduce()  操作需要一个初始值和一个 BinaryOperator 函数
//        BinaryOperator两进一出 实现了BiFuction接口
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
        int sum = numbers.stream()
                .reduce(0, (a, b) -> a + b);
        System.out.println(sum); // 输出 15

//          joining操作--对string操作添加分隔符
        List<String> strings = Arrays.asList("apple", "banana", "orange");
        String joinedString = strings.stream().collect(Collectors.joining(", "));
        System.out.println(joinedString); // 输出 "apple, banana, orange"
    }
}
